<?php

namespace builder\widget\ajax;

use builder\helper\H5;
use builder\helper\Url;
use builder\widget\BaseWidget;
use yii\base\InvalidArgumentException;
use yii\helpers\Json;

/**
 * 块组件(page)
 * ```php
 *  WidgetFacade::echo2Return(function () {
 *              BlockPage::begin([
 *                 'url' => 'user/create',
 *                 'scope' => [
 *                     'param1' => 'default.Field1',
 *                 ],
 *              ]);
 *              echo '<button class="layui-btn layui-btn-sm layui-bg-light layui-border-theme"><i class="bi bi-box-arrow-in-down-right"></i> 动态按钮(page)</button>';
 *              BlockPage::end();
 * });
 *
 * ```
 */
class BlockPage extends BaseWidget
{
    /**
     * @var array|string ajax路由/地址
     */
    public $url;

    /**
     * @var string 目标窗口，仅 _self、_blank、_top、_parent。
     */
    public $target = '_self';

    /**
     * @var string 调用者，仅 self（当前窗口对象和window同等）、parent、top。
     */
    public $frame = 'self';

    /**
     * angular字段
     * @var null|array
     */
    public $scope = null;

    /**
     * @var array 其他选项，如：attribute、class、style。
     */
    public $options = [];

    /**
     * @return void
     */
    public function initOptions()
    {
        if (empty($this->url)) {
            throw new InvalidArgumentException('The class ' . __CLASS__ . '::url is empty.');
        }

        $this->url = Url::to($this->url, '');
    }

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        $this->initOptions();

        echo H5::beginTag('ngx-block', array_merge($this->options, [
                'type' => 'page',
                'url' => $this->url,
                'target' => $this->target,
                'frame' => $this->frame,
                'scope' => $this->scope ? Json::htmlEncode($this->scope) : '',

            ])) . "\n";
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        echo H5::endTag('ngx-block') . "\n";
    }
}